package com.edgclub.edg.activity;


import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.edgclub.edg.R;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.UserApi;
import com.edgclub.edg.api.param.UserParam;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.model.User;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.umeng.analytics.MobclickAgent;

import java.util.Timer;
import java.util.TimerTask;

public class RegisterActivity extends GzBaseTooolBarActivity implements View.OnClickListener , VolleyListener{
    private EditText phone , mess_code;
    private Button get_code_btn , submit;
    private CheckBox agree;
    private TextView user_protocol;

    private int time = 120;
    private Timer timer;
    private TimerTask timerTask;
    private String type , type1;
    private RelativeLayout user_rules;
    private UserPrefUtils userPrefUtils;
    private User user;

    @Override
    public int getContentView() {
        return R.layout.activity_register;
    }

    @Override
    public void setTitleBarView() {
        type = getIntent().getStringExtra("getpsw")+"";
        type1 = getIntent().getStringExtra("zhuce")+"";
        setCustomActionBar();
        if ("1".equals(type)){
            title.setText("重置密码");
        }
        if ("2".equals(type)){
            title.setText("绑定手机");
        }
        else if("3".equals(type1)){
            title.setText("欢迎注册EDG俱乐部");
        }
        main_back.setVisibility(View.VISIBLE);
        main_back.setOnClickListener(this);
    }

    @Override
    public void initView() {
        phone = (EditText) findViewById(R.id.phone);
        mess_code = (EditText) findViewById(R.id.mess_code);
        get_code_btn = (Button) findViewById(R.id.get_code_btn);
        user_rules = (RelativeLayout) findViewById(R.id.user_rules);
        if ("1".equals(type)||"2".equals(type)){
            user_rules.setVisibility(View.GONE);
        }else{
            user_rules.setVisibility(View.VISIBLE);
        }
        submit = (Button) findViewById(R.id.submit);
        agree = (CheckBox) findViewById(R.id.agree);
        user_protocol = (TextView) findViewById(R.id.user_protocol);

        get_code_btn.setOnClickListener(this);
        submit.setOnClickListener(this);
        agree.setOnClickListener(this);
        agree.setChecked(true);
        user_protocol.setOnClickListener(this);


    }

    @Override
    public void initData() {
        userPrefUtils = new UserPrefUtils(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.submit:
                if ("2".equals(type)) {
                    boundphone();
                }else{
                    oksubmit();
                }


                break;
            case R.id.main_back:
                finish();
                break;
            case R.id.get_code_btn:
                getCode();
                break;
            case R.id.user_protocol:
                Intent intent1=new Intent(this,GzWebViewActivity.class);
                intent1.putExtra("url", ApiConfig.USER_PROTOCOL_URL);
                intent1.putExtra("right_btn",true);
                startActivity(intent1);
                break;
        }
    }
    private void getCode(){
        String strPhone = phone.getText().toString().trim();
        if(TextUtils.isEmpty(strPhone)){
            Toast.makeText(RegisterActivity.this,"请输入你的手机号",Toast.LENGTH_SHORT).show();
            return;
        }
        if (!StringUtils.isPhoneNum(strPhone)) {
            Toast.makeText(RegisterActivity.this,"手机格式不正确",Toast.LENGTH_SHORT).show();
            return;
        }
        UserParam param = new UserParam();
        param.setUid(strPhone);
        if("1".equals(type)){
            param.setTarget("forgetPwd");
        }
        else if("2".equals(type)){
            param.setTarget("bound");
        }
        else {
            param.setTarget("register");
        }
        new UserApi(this).registerGetcode(param,this);

    }
    public void oksubmit() {
        if (TextUtils.isEmpty(phone.getText().toString().trim())) {
            Toast.makeText(RegisterActivity.this,"请输入手机号码",Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(mess_code.getText().toString().trim())) {
            Toast.makeText(RegisterActivity.this,"请输验证码",Toast.LENGTH_SHORT).show();
            return;
        }

        if(!agree.isChecked()){
            Toast.makeText(RegisterActivity.this,"请仔细阅读用户协议",Toast.LENGTH_SHORT).show();
            return;
        }
        String strPhone = phone.getText().toString().trim();
        UserParam param = new UserParam();
        param.setUid(strPhone);
        if ("1".equals(type)){
            param.setTarget("forgetPwd");
            param.setCode(mess_code.getText().toString().trim());
        }
        else {
            param.setTarget("register");
            param.setCode(mess_code.getText().toString().trim());
        }
        new UserApi(this).registerCode(param,this);

    }

    public void boundphone(){
        String strPhone = phone.getText().toString().trim();
        UserParam param = new UserParam();
        param.setUserId(userPrefUtils.getUser().getId());
        param.setPhone(strPhone);
        param.setOldPhone(userPrefUtils.getUser().getPhone()+"");
        param.setVerifyCode(mess_code.getText().toString().trim());
        new UserApi(this).boundPhone(param,this);
    }


    @Override
    public void onStart(String tag) {
        if (ApiConfig.APIURL.URL_REGISTER_CODE .equals(tag)) {
            showDialog(StringUtils.getString(R.string.get_identifying), false);
        }else if (ApiConfig.APIURL.URL_REGISTER_CODE1 .equals(tag)){
            showDialog(StringUtils.getString(R.string.get_login), false);
        }
        else if (ApiConfig.APIURL.URL_BOUND_PHONE .equals(tag)){
            showDialog(StringUtils.getString(R.string.bound_login), false);
        }
    }

    @Override
    public void onSuccess(String response, String tag) {
        dismissDialog();
        if (ApiConfig.APIURL.URL_REGISTER_CODE .equals(tag)) {
            if (JSONHelper.isSuccess(response)) {
                Toast.makeText(RegisterActivity.this, StringUtils.getString(R.string.checkverification),
                        Toast.LENGTH_LONG).show();
                get_code_btn.setEnabled(false);
                startTimer();

            } else if (JSONHelper.getResultCode(response) == 1010) {

                if ("2".equals(type)){
                    Toast.makeText(RegisterActivity.this,
                            StringUtils.getString(R.string.phoneisregster_bound), Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(RegisterActivity.this,
                            StringUtils.getString(R.string.phoneisregster), Toast.LENGTH_LONG).show();
                }
            }
            else if (JSONHelper.getResultCode(response) == 1003) {
                Toast.makeText(RegisterActivity.this,
                        StringUtils.getString(R.string.verificationerror), Toast.LENGTH_LONG).show();

            }
            else if (JSONHelper.getResultCode(response) == 4001) {
                Toast.makeText(RegisterActivity.this,
                        StringUtils.getString(R.string.phoneisregster1), Toast.LENGTH_LONG).show();

            }
            else {
                Toast.makeText(
                        RegisterActivity.this,
                        StringUtils.getString(R.string.verificationfail) + ":code(" + JSONHelper.getResultCode(response)
                                + ")", Toast.LENGTH_LONG).show();
            }
        }else if (ApiConfig.APIURL.URL_REGISTER_CODE1 .equals(tag)){
            if (JSONHelper.isSuccess(response)) {
                    Intent intent = new Intent(this, RegisterSetPassActivity.class);
                    intent.putExtra("verifyCode", mess_code.getText().toString().trim());
                    intent.putExtra("phone", phone.getText().toString().trim());
                    intent.putExtra("type", type);
                    startActivity(intent);
                    MobclickAgent.onEvent(this,"EC_PHONE_REGISTER_SUCCESS");

            }
            else if (JSONHelper.getResultCode(response) == 1003) {
                Toast.makeText(RegisterActivity.this,
                        StringUtils.getString(R.string.verificationerror), Toast.LENGTH_LONG).show();

            }
        }else if (ApiConfig.APIURL.URL_BOUND_PHONE .equals(tag)){
            if (JSONHelper.isSuccess(response)) {
                user = userPrefUtils.getUser();
                user.setPhone(phone.getText().toString().trim());
                userPrefUtils.saveUser(user);
                Toast.makeText(this,"绑定成功",Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    @Override
    public void onFaile(VolleyError volleyError, String tag) {
            dismissDialog();
            ResultCode.toastVolleyError(RegisterActivity.this, volleyError);
    }

    class CountDownTimerTask extends TimerTask {

        @Override
        public void run() {
            handler.sendEmptyMessage(0);
        }
    }
    private void startTimer() {
        get_code_btn.setBackgroundResource(R.drawable.register_selector);
        get_code_btn.setTextColor(getResources().getColor(R.color.c5));
        time = 60;
        if (null == timer) {
            timer = new Timer();
        }

        timerTask = new CountDownTimerTask();
        timer.schedule(timerTask, 1000, 1000);
    }

    private void stopTimer() {
        get_code_btn.setBackgroundResource(R.drawable.shape_gz_get_code_bg);
        get_code_btn.setTextColor(getResources().getColor(R.color.c10));
        if (null != timer) {
            timer.cancel();
            timer = null;
        }

        if (null != timerTask) {
            timerTask.cancel();
        }

    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0:
                    time--;
                    get_code_btn.setText(time + StringUtils.getString(R.string.sresend));
                    if (time == 0) {
                        stopTimer();
                        time = 60;
                        get_code_btn.setEnabled(true);
                        get_code_btn.setText(StringUtils.getString(R.string.sendverification));
                    }
                    break;

                default:
                    break;
            }
            super.handleMessage(msg);
        }

    };
}
